package com.linln.common.websocket;


import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy;
import org.apache.logging.log4j.core.appender.rolling.TriggeringPolicy;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.springframework.stereotype.Controller;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.nio.charset.Charset;


@ServerEndpoint("/websocketHandle/{typeId}")
@Controller    //此注解千万千万不要忘记，它的主要作用就是将这个监听器纳入到Spring容器中进行管理
public class WebsocketHandle {

    /**
     * WebSocket请求开启
     */
    @OnOpen
    public void onOpen(@PathParam("typeId")String typeId, Session session) {
          //系统监控状态
     //   System.out.println(typeId);
         if("001".equals(typeId)){
             try {
                 // 启动新的线程
                 SystemStatusThread thread = new SystemStatusThread(session);
                 thread.start();
             } catch (Exception ex) {
                 ex.printStackTrace();
             }

         }


        //系统监控状态
        if("002".equals(typeId)){

            try {
                createDomainAppender(session);

            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    }

    /**
     * WebSocket请求关闭，关闭请求时调用此方法，关闭流
     */
    @OnClose
    public void onClose() {

    }

    @OnError
    public void onError(Throwable thr) {
        thr.printStackTrace();
    }


    public  void createDomainAppender(Session session){
        final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        final org.apache.logging.log4j.core.config.Configuration config = ctx.getConfiguration();
        if (config.getAppender("WritersAppender") != null) {

            WritersAppender appender =config.getAppender("WritersAppender");
            appender.session = session;
            return;
        }
        final PatternLayout layout = PatternLayout.newBuilder()
                .withCharset(Charset.forName("UTF-8"))
                .withConfiguration(config)
                .withPattern("%d %t %p %X{TracingMsg} %c - %m%n")
                .build();
        final TriggeringPolicy policy = TimeBasedTriggeringPolicy.newBuilder()
                .withModulate(true)
                .withInterval(1)
                .build();
         WritersAppender  appender = new WritersAppender(session,"WritersAppender",null,layout,true);
        config.getLoggerConfig("org.hibernate.SQL").addAppender(appender, Level.DEBUG, null);
        config.getRootLogger().addAppender(appender, Level.INFO, null);
        appender.start();
        config.addAppender(appender);
        ctx.updateLoggers(config);
    }
}

